package com.ktjy.goods.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.core.page.TableDataInfo;
import com.ktjy.common.enums.BusinessType;
import com.ktjy.goods.domain.Brand;
import com.ktjy.goods.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 品牌管理Controller
 *
 * @author ktjy
 * @date 2025-03-17
 */
@RestController
@RequestMapping("/goods/brand")
public class BrandController extends BaseController
{
    @Autowired
    private IBrandService brandService;

/**
 * 查询品牌管理列表
 */
@PreAuthorize("@ss.hasPermi('goods:brand:list')")
@GetMapping("/list")
    public TableDataInfo list(Brand brand)
    {
        startPage();
        List<Brand> list = brandService.selectBrandList(brand);
        return getDataTable(list);
    }


    /**
     * 导出品牌管理列表
     */
    @PreAuthorize("@ss.hasPermi('goods:brand:export')")
    @Log(title = "品牌管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Brand brand)
    {
        List<Brand> list = brandService.selectBrandList(brand);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Brand brand1 = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("id", brand1.getId());
            exportData.put("name",brand1.getName());
            exportData.put("logoUrl", brand1.getLogoUrl());

            String enabled="正常";

            if (brand1.getEnabled() == 1){
                enabled="停用";
            }

            exportData.put("enabled", enabled);
            exportData.put("remark",brand1.getRemark());

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }

        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
        writer.addHeaderAlias("id", "品牌id");
        writer.addHeaderAlias("name", "品牌名称");
        writer.addHeaderAlias("logoUrl", "品牌logo");
        writer.addHeaderAlias("enabled", "是否启用");
        writer.addHeaderAlias("remark", "备注");

        writer.write(exportList, true);

        // 自动调整列宽
        writer.autoSizeColumnAll();

        // 设置最小列宽
        int minColumnWidth = 20; // 可以根据需要调整最小列宽
        int columnCount = writer.getSheet().getRow(0).getLastCellNum();
        for (int i = 0; i < columnCount; i++) {
            int width = writer.getSheet().getColumnWidth(i);
            if (width < minColumnWidth * 256) {
                writer.getSheet().setColumnWidth(i, minColumnWidth * 256);
            }
        }


        try {
            // 设置浏览器响应的格式
            String fileName = URLEncoder.encode("用户信息", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        }catch (Exception e){
            System.out.println(e);
        }
    }

    /**
     * 获取品牌管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('goods:brand:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(brandService.getById(id));
    }

    /**
     * 新增品牌管理
     */
    @PreAuthorize("@ss.hasPermi('goods:brand:add')")
    @Log(title = "品牌管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Brand brand)
    {
        return toAjax(brandService.save(brand));
    }

    /**
     * 修改品牌管理
     */
    @PreAuthorize("@ss.hasPermi('goods:brand:edit')")
    @Log(title = "品牌管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Brand brand)
    {
        return toAjax(brandService.updateById(brand));
    }

    /**
     * 删除品牌管理
     */
    @PreAuthorize("@ss.hasPermi('goods:brand:remove')")
    @Log(title = "品牌管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(brandService.removeByIds(ids));
    }
}